package com.nchuAo.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.nchuAo.auth.service.TokenService;
import com.nchuAo.constants.TokenConstants;
import com.nchuAo.entity.LoginUser;
import com.nchuAo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TokenServiceImpl implements TokenService {
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private StringRedisTemplate redisTemplate;
	//1. 生成token信息
	@Override
	public Map<String, Object> createToken(LoginUser loginUser) {
		String token = loginUser.getToken();
		//1.1 第一件事：将用户信息存放到redis中
		redisTemplate.opsForValue().set(TokenConstants.REDIS_PREFIX + token, JSON.toJSONString(loginUser));

		//第二件事：将通过jwt加密后的用户信息返回到前端
		//1.1  定义数据map
		Map<String, Object> map = new HashMap<>();
		// map.put("username",loginUser.getUser().getUsername());
		// map.put("userId",loginUser.getUser().getId());
		map.put(TokenConstants.JWT_TOKEN,token);

		//2.2 将上面的数据map进行加密
		String jwtToken = jwtUtil.createToken(map);
		//2.3 定义返回Map
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put(TokenConstants.JWT_ACCESS_TOKEN,jwtToken);

		return resultMap;
	}

	public static void main(String[] args) {
		JwtUtil jwtUtil = new JwtUtil();
		String token = "eyJhbGciOiJIUzI1NiJ9.eyJ0b2tlbiI6ImZlMmNlNzUzLTlmMGYtNGVlMi1iNzExLWEzODZiZmZkYjYzMSJ9.nZVnpVJyqZMLrqqtVdyAWex18w4gVYKJpJwxpSFsW6Q";
		Claims claims = jwtUtil.parseToken(token);
		Object token1 = claims.get("token");
		System.out.println("token1 = " + token1);
		String redisKey = "nchuAo_login_token:" + token1;

	}
}
